import { dictUrl } from '../../../../api/index'
import { preImgUrl } from '../../../../api/config'
import { entryInfoUrl, entrySaveUrl, userInfoUrl, userUpdateeInfoUrl, studyListUrl } from '../../../../api/individual'
import { post, get, uploadFile, initUploadFileListKey, formatDate } from '../../../../utils/index'
import WxValidate from '../../../../utils/WxValidate'
import Dialog from '@vant/weapp/dialog/dialog'

Page({
  data: {
    page: '',
    readonly: false,
    isEdit: false,
    bgList: ['blue-color-bg', 'yellow-color-bg', 'green-color-bg', 'pink-color-bg', 'purple-color-bg'],
    title: '教育经历',
    info: {},
    studys: [],
    form: { academicCertificateFileList: [] },
    formError: {},
    academicPopup: false,
    academicTypePopup: false,
    datePopup: false,
    academicColumns: [],
    academicTypeColumns: [],
    currentDate: new Date().getTime(),
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      }
      if (type === 'month') {
        return `${value}月`
      }
      return `${value}日`
    }
  },
  async loadData () { // 获取人员信息
    const url = this.data.page === 'entry' ? entryInfoUrl : userInfoUrl
    let { data, data: { studys } } = await post(url)
    studys.forEach(item => {
      item.level = Number(item.academic)
      item.academicName = item.academicDictBiz && item.academicDictBiz.dictValue
      item.academicTypeName = item.academicTypeDictBiz && item.academicTypeDictBiz.dictValue
      item.academicCertificateFileList = []
      if (item.academicCertificateFile && item.academicCertificateFile.link) {
        const academicCertificateFile = initUploadFileListKey(item.academicCertificateFile)
        item.academicCertificateFileList = [academicCertificateFile]
      }
    })
    if (data.status === 3 || data.status === 4) {
      const { data: { rows } } = await get(studyListUrl, { page: 1, pageSize: 30 })
      rows.forEach(item => {
        item.isDeleted = 0
        item.graduationDate = item.endDate
        item.academicName = item.academic && item.academic.dictValue
        item.academic = item.academic && item.academic.dictKey
        item.level = Number(item.academic)
        item.academicTypeName = item.academicType && item.academicType.dictValue
        item.academicType = item.academicType && item.academicType.dictKey
        item.academicCertificateFileList = []
        if (item.attachmentUrl) {
          const academicCertificateFile = {
            link: item.attachmentUrl,
            address: `${preImgUrl}${item.attachmentUrl}`
          }
          item.academicCertificateFileId = -1
          item.academicCertificateFile = initUploadFileListKey(academicCertificateFile)
          item.academicCertificateFileList = [item.academicCertificateFile]
        }
      })
      studys = rows
    }
    this.setData({ info: data, studys })
  },
  async loadAcademic () { // 学历类型
    const { data } = await get(dictUrl, { code: 'education_background' })
    this.setData({ academicColumns: data })
  },
  async loadAcademicType () { // 户口性质字典
    const { data } = await get(dictUrl, { code: 'academic_type' })
    this.setData({ academicTypeColumns: data })
  },
  save () { // 保存
    const { form, studys, info, editIndex } = this.data
    if (!this.WxValidate.checkForm(form)) {
      const formError = this.WxValidate.formError
      this.setData({ formError })
      wx.showToast({ title: '信息填写有误，请检查', icon: 'none' })
      return
    }
    this.setData({ formError: {} })
    if (editIndex > -1) {
      studys[editIndex] = form
    } else {
      studys.push(form)
    }
    info.studys = studys
    this.submit()
  },
  async submit () { // 提交
    const { page } = this.data
    const url = page === 'entry' ? entrySaveUrl : userUpdateeInfoUrl
    await post(url, this.data.info)
    this.loadData()
    this.setData({ isEdit: false, editIndex: -1, title: '教育经历' })
  },
  addStudy () { // 添加教育经历
    const form = { academicCertificateFileList: [] }
    this.setData({ form, isEdit: true, title: '添加教育经历' })
  },
  async addAgain () { // 继续添加
    const { form, studys, info, editIndex, page } = this.data
    if (!this.WxValidate.checkForm(form)) {
      const formError = this.WxValidate.formError
      this.setData({ formError })
      wx.showToast({ title: '信息填写有误，请检查', icon: 'none' })
      return
    }
    if (editIndex > -1) {
      studys[editIndex] = form
    } else {
      studys.push(form)
    }
    info.studys = studys
    const url = page === 'entry' ? entrySaveUrl : userUpdateeInfoUrl
    await post(url, this.data.info)
    const againForm = { academicCertificateFileList: [] }
    this.setData({ form: againForm, isEdit: true, editIndex: -1, title: '添加教育经历' })
  },
  editStudy ({ currentTarget }) { // 编辑教育经历
    if (this.data.readonly) {
      return
    }
    const { index } = currentTarget.dataset
    const form = this.data.studys[index]
    this.setData({ form, isEdit: true, title: '编辑教育经历', editIndex: index })
    this.initValidator()
  },
  delStudy ({ target, detail }) { // 删除教育经历
    const { instance } = detail
    Dialog.confirm({
      message: '确定删除该教育经历吗？',
    }).then(() => {
      instance.close()
      const { index } = target.dataset
      console.log(index)
      if (this.data.info.status === 3 || this.data.info.status === 4) {
        this.data.studys[index].isDeleted = 1
        this.data.info.studys = this.data.studys
      } else {
        this.data.studys.splice(index, 1)
      }
      this.submit()
    }).catch(() => {
      instance.close()
      Dialog.close()
    })
  },
  schoolChange ({ detail }) { // 毕业学校
    this.setData({ 'form.school': detail })
  },
  academicClick () { // 学历弹窗
    wx.hideKeyboard()
    this.setData({ academicPopup: true })
  },
  academicClose () { // 学历取消
    this.setData({ academicPopup: false })
  },
  academicConfirm ({ detail }) { // 学历确认
    const { value } = detail
    this.setData({
      'form.academic': value.dictKey,
      'form.academicName': value.dictValue,
      'form.level': Number(value.dictKey)
    })
    this.academicClose()
  },
  academicTypeClick () { // 学历类型弹窗
    wx.hideKeyboard()
    this.setData({ academicTypePopup: true })
  },
  academicTypeClose () { // 学历类型取消
    this.setData({ academicTypePopup: false })
  },
  academicTypeConfirm ({ detail }) { // 学历类型确认
    const { value } = detail
    this.setData({
      'form.academicType': value.dictKey,
      'form.academicTypeName': value.dictValue
    })
    this.academicTypeClose()
    this.initValidator()
  },
  majorChange ({ detail }) { // 所学专业
    this.setData({ 'form.major': detail })
  },
  dateClick () { // 弹窗
    wx.hideKeyboard()
    this.setData({ datePopup: true })
  },
  dateChange ({ detail }) { // 选择日期
    const graduationDate = formatDate(new Date(detail), 'yyyy-MM-dd')
    this.setData({ 'form.graduationDate': graduationDate })
    this.dateClose()
  },
  dateClose () { // 关闭时间选择
    this.setData({ datePopup: false })
  },
  async academicCertificateFileRead ({ detail }) { // 毕业证上传
    const { file } = detail
    let { data } = await uploadFile(file.path)
    data = initUploadFileListKey(data)
    this.setData({ 'form.academicCertificateFileList': [data] })
    this.data.form.academicCertificateFile = data
    this.data.form.academicCertificateFileId = data.id
  },
  academicCertificateFileDel () { // 毕业证删除
    this.data.form.academicCertificateFile = {}
    this.data.form.academicCertificateFileId = ''
    this.setData({ 'form.academicCertificateFileList': [] })
  },
  onClickLeft () { // 返回
    if (this.data.isEdit) {
      this.setData({ isEdit: false, title: '教育经历' })
      this.loadData()
      return
    }
    wx.navigateBack({})
  },
  initValidator () { // 初始化验证器
    const rules = {
      school: { required: true },
      academic: { required: true },
      academicType: { required: true }
    }
    const messages = {
      school: { required: '请输入毕业学校' },
      academic: { required: '请选择学历' },
      academicType: { required: '请选择学历类型' }
    }
    if (this.data.form.level < 7) {
      rules.major = { required: true }
      messages.major = { required: '请输入所学专业' }
      rules.graduationDate = { required: true }
      messages.graduationDate = { required: '请选择毕业时间' }
    }
    if (this.data.form.level < 5) {
      rules.academicCertificateFileId = { required: true }
      messages.academicCertificateFileId = { required: '请上传毕业证' }
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  readonlyChange () { // 编辑资料
    this.setData({ readonly: false })
  },
  onLoad (options) {
    // page表示从哪个页面过来的, entry->入职； change->修改；me->我的
    const { page } = options
    const readonly = page === 'me'
    this.setData({ readonly, page })
    this.loadData()
    this.loadAcademic()
    this.loadAcademicType()
    this.initValidator()
  }
})